package com.cola.action;

import com.cola.entity.User;
import com.cola.entity.WeChatInfo;
import com.cola.service.UserService;
import com.cola.service.auth.WeChatService;
import com.cola.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * 微信授权Action
 * @author Max
 * @since 2017/9/12
 */
public class AuthAction extends BaseAction {
    private static final Logger logger = LoggerFactory.getLogger(AuthAction.class);
    private Integer login_type ;//登录类型

    private String code;

    /**
     * 跳转到授权引导页
     * @author Max
     * @since 2017/9/12
     */
    public String toAuth(){
        return SUCCESS;
    }


    /**
     * 微信授权
     * @author Max
     * @since 2017/9/12
     */
    public String auth(){
        //配置分享的链接
        logger.info("进入微信授权--->根据code获取微信用户信息！");
        WeChatInfo weChatInfo = getWeiXin();
        if(weChatInfo!=null){
            //将用户微信信息存入Redis
            saveWeChatInfoToRedisCookie(weChatInfo);

            //判断是否关注
            Integer sub = getSubscribeInfo(weChatInfo.getOpenid());
            if(sub<1){
                setWxMessage();
                return SUBSCRIBE;
            }

            setRequestAttribute("isSubscribe", sub);
            setRequestAttribute("openId", weChatInfo.getOpenid());
            setRequestAttribute("nickname", weChatInfo.getNickname());
            setWxMessage();
            //从redis中获取用户信息
            User user = getUserInfoFromRedis();
            if(user!=null){
                // 更新用户的微信信息
                if(UserService.getInstance().checkUserInfo(user.getMobile(),weChatInfo.getOpenid(),user.getUserType())){
                    // 重新获取用户信息存入Redis
                    boolean a = UserService.getInstance().updateUserWeChatInfo(weChatInfo,user.getUserType());
                    user.setWeChatInfo(weChatInfo);
                    boolean b = saveUserInfoToRedisCookie(user,getLoginTypeFromCookie());

                    //根据用户类型跳转到不同的页面
                    if(a && b){
                        switch (user.getUserType()){
                            case "SHOP":return SHOP_INDEX;
                            case "MEP":return MEP_INDEX;
                            case "COURIER":return COURIER_INDEX;
                            default:return ERROR_500;
                        }
                    }else{
                        return ERROR_500;
                    }
                }
            }
            //TODO 根据openID 获取用户信息 如果没有该用户信息，则跳转到登录页面
            return LOGIN;
        }else{
            setRequestAttribute("login_type",login_type);
            return AGAIN;
        }
    }


    /**
     * 微信回调函数，获取用户微信id
     * @return Map<String,Object>
     * @author Max
     * @since 2017/9/12
     */
    private WeChatInfo getWeiXin(){
        String openid="";
        String accessToken="";
        //判断code是否为空
        if(StringUtils.isNotEmpty(code)){
            WeChatService weChatService = new WeChatService();
            //根据code获取access_token，和openid
            Map<String,String> tokenMap=weChatService.getAccessToken(code);
            //判断token，和openid的map是否为空
            logger.info("tokenMap======"+tokenMap);
            if(getSessionAttribute("tokenMap")!=null){
                getRequest().removeAttribute("tokenMap");
                setRequestAttribute("tokenMap", tokenMap);
            }
            if(tokenMap.size()!=0){
                openid=tokenMap.get("openid");
                accessToken=tokenMap.get("access_token");
                //根据access_token，和openid获取微信用户详情
                if(StringUtils.isNotEmpty(accessToken)&&StringUtils.isNotEmpty(openid)){
                    return weChatService.getWeChatUserInfo(accessToken,openid);
                }
            }
        }
        return null;
    }


    /**
     * 跳转到各个页面时配置页面wx信息
     * @author Max
     * @since 2017/9/12
     */
    private void setWxMessage(){
        String jsapi_ticket= WeChatUtils.getJsApiTicket();
        String requestUrl = getRequestUrl(getRequest());
        long timestamp = System.currentTimeMillis();//时间戳
        String noncestr = NonceStrUtils.generateCommonStr(16);//随机字符串
        String SHA1data = "jsapi_ticket="+jsapi_ticket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+requestUrl;
        String signature = new SHA1().getDigestOfString(SHA1data.getBytes());
        //设置分享链接
        setRequestAttribute("shareUrl", PropertyUtils.getProperty("sendfriendurl"));
        setRequestAttribute("appid", PropertyUtils.getProperty("appid"));
        setRequestAttribute("signature", signature);
        setRequestAttribute("timestamp", timestamp);
        setRequestAttribute("noncestr", noncestr);
        setRequestAttribute("url", PropertyUtils.getProperty("url"));
    }

    /**
     * 获取关注记录
     * @param openId
     * @return Integer
     * @author Max
     * @since 2017/9/12
     */
    private static int  getSubscribeInfo(String openId) {
        String baseInfoString="";
        try {
            String url=PropertyUtils.getProperty("baseInfoUrl");
            url= HttpUtils.getParms(url,"access_token", WeChatUtils.getAccessToken());
            url= HttpUtils.getParms(url,"openId",openId);
            url= HttpUtils.getParms(url,"lang","zh_CN");
            baseInfoString=HttpUtils.sendGet(url);
            if(baseInfoString.equals("error")){
                return -1;
            }else{
                JSONObject jsonResult = new JSONObject(baseInfoString);
                if(jsonResult.has("subscribe")){
                    return jsonResult.getInt("subscribe");
                }else{
                    return -1;
                }
            }
        } catch (Exception e) {
            logger.error("获取用户详情接口异常：",e);
            return -1;
        }
    }


    public static void main(String[] args) {
        if(!false&&true){
            System.out.println(true);
        }
    }

    public Integer getLogin_type() {
        return login_type;
    }

    public void setLogin_type(Integer login_type) {
        this.login_type = login_type;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
}
